package com.android.namecard.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.namecard.R;
import com.android.namecard.entity.Namecard;
import com.android.namecard.model.NamecardDBHelper;
import com.android.namecard.util.BluetoothChatService;

public class SendTypeActivity extends Activity{
	
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_READ_FRONT_IMAGE = 21;
    public static final int MESSAGE_READ_BACK_IMAGE = 22;
    public static final int MESSAGE_READ_INFO = 23;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_SAVE = 6;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.send_type);
        
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙服务不可用", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        Button hasSoftwareBut = (Button)findViewById(R.id.has_software);
        Button hasNoSoftwareBut = (Button)findViewById(R.id.has_no_software);
        
        hasSoftwareBut.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
	            Intent serverIntent = new Intent(SendTypeActivity.this, DeviceListActivity.class);
	            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			}
        });
        
        hasNoSoftwareBut.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendNamecard();
			}
        });
    }
    
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }
    
    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }
    
    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendNamecard_HasSoftware() {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, "没有连接设备", Toast.LENGTH_SHORT).show();
            return;
        }
        
        NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
        Namecard namecard = namecardDB.getNamecard();
        Bitmap frontBitmap = namecard.getFrontImage();
        byte[] frontByte = NamecardDBHelper.getByteOfBitmap(frontBitmap);
        Bitmap backBitmap = namecard.getBackImage();
        byte[] backByte = NamecardDBHelper.getByteOfBitmap(backBitmap);
        String infoString = namecard.encodeInfo();
        byte[] infoByte = infoString.getBytes();
        // Check that there's actually something to send
        if (frontByte.length > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            mChatService.write(frontByte);
            mChatService.write(backByte);
            mChatService.write(infoByte);
            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            //mOutEditText.setText(mOutStringBuffer);
        }
        Toast.makeText(getApplicationContext(), "名片传输完毕", Toast.LENGTH_SHORT).show();
    }

    private Bitmap frontBitmap = null;
    private Bitmap backBitmap = null;
    private String infoString = null;
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
//                    mTitle.setText(R.string.title_connected_to);
//                    mTitle.append(mConnectedDeviceName);
                    break;
                case BluetoothChatService.STATE_CONNECTING:
//                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
//                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
//                byte[] writeBuf = (byte[]) msg.obj;
                break;
            case MESSAGE_READ:
//                byte[] readBuf = (byte[]) msg.obj;
//                // construct a string from the valid bytes in the buffer
//                Bitmap frontBitmap = NamecardDBHelper.getBitmapOfByte(readBuf);
                break;
            case MESSAGE_READ_FRONT_IMAGE:
            	byte[] frontBuf = (byte[]) msg.obj;
            	frontBitmap = BitmapFactory.decodeByteArray(frontBuf, 0, msg.arg1);
            	break;
            case MESSAGE_READ_BACK_IMAGE:
            	byte[] backBuf = (byte[]) msg.obj;
            	backBitmap = BitmapFactory.decodeByteArray(backBuf, 0, msg.arg1);
            	break;
            case MESSAGE_READ_INFO:
            	byte[] infoBuf = (byte[]) msg.obj;
            	infoString = new String(infoBuf, 0, msg.arg1);
            	break;
            case MESSAGE_SAVE:
            	long markTime = System.currentTimeMillis();
            	while(infoString==null || backBitmap==null || frontBitmap== null){
            		//阻塞
            		if(System.currentTimeMillis()-markTime>=5000){
            			Toast.makeText(getApplicationContext(), "数据出错，传输失败 ", Toast.LENGTH_SHORT).show();
            			return;
            		}
            	}
            	NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
            	if(namecardDB.insertNamecardByReceive(infoString, frontBitmap, backBitmap)){
            		Toast.makeText(getApplicationContext(), "名片传输完毕！", Toast.LENGTH_SHORT).show();
            	}else{
            		Toast.makeText(getApplicationContext(), "数据库写入出错！", Toast.LENGTH_SHORT).show();
            	}
            	break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "连接到 "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChatService.connect(device);
                
                sendNamecard_HasSoftware();
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, "蓝牙服务不可用", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.option_menu, menu);
//        return true;
//    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//        case R.id.scan:
//            // Launch the DeviceListActivity to see devices and do scan
//            Intent serverIntent = new Intent(this, DeviceListActivity.class);
//            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
//            return true;
//        case R.id.discoverable:
//            // Ensure this device is discoverable by others
//            ensureDiscoverable();
//            return true;
//        }
//        return false;
//    }
    
    File frontFile = null;
    File backFile = null;
	private void sendNamecard(){
    	NamecardDBHelper namecardDB = new NamecardDBHelper(getBaseContext());
    	Namecard namecard = namecardDB.getNamecard();

    	try {
			//frontFile = File.createTempFile("front_namecard", ".jpg");
			frontFile = new File("/sdcard/","front_namecard.jpg");
			FileOutputStream fontOutputStream = new FileOutputStream(frontFile);
			namecard.getFrontImage().compress(CompressFormat.JPEG, 100, fontOutputStream);
			
			backFile = new File("/sdcard/","back_namecard.jpg");
			FileOutputStream backOutputStream = new FileOutputStream(backFile);
			namecard.getBackImage().compress(CompressFormat.JPEG, 100, backOutputStream);
			
			frontFile.deleteOnExit();
			backFile.deleteOnExit();
			
			sendFile(frontFile);
//			sendFile(backFile);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			namecardDB.close();
		}
    }
	
	private void sendFile(File file){
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		startActivity(Intent.createChooser(intent, "共享文件"));
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			System.exit(0);
			return true;
		}
		return false;
	}
}
